//
//  XMPPChatManager.m
//  LTChat
//
//  Created by apple on 4/9/14.
//  Copyright (c) 2014 fantasy. All rights reserved.
//

#import "XMPPChatManager.h"
#import "DDTTYLogger.h"

@interface XMPPChatManager()
<
    XMPPStreamDelegate,
    XMPPRosterDelegate
>
{
    NSInteger actionType;
}
@property(nonatomic,strong)XMPPConfig *xmppConfig;
@property (nonatomic,strong)NSString *XMPPmyJID;
@property (nonatomic,strong)NSString *XMPPmyPassword;

@property (nonatomic,strong)XMPPStream *innerxmppStream;
@property (nonatomic,readonly)XMPPReconnect *innerxmppReconnect;
@property (nonatomic,readonly)XMPPRoster *innerxmppRoster;
@property (nonatomic,strong)XMPPRosterCoreDataStorage *innerxmppRosterStorage;


@property (nonatomic)BOOL allowSelfSignedCertificates;
@property (nonatomic)BOOL allowSSLHostNameMismatch;

-(id)initWithConfig:(XMPPConfig *)config;

@end

@implementation XMPPChatManager

-(void)dealloc
{
    [self teardownStream];
}

- (void)teardownStream
{
	[_innerxmppStream removeDelegate:self];
	[_innerxmppReconnect deactivate];
	[_innerxmppRoster deactivate];
	[_innerxmppStream disconnect];
	
	_innerxmppStream = nil;
    _innerxmppReconnect = nil;
	_innerxmppRoster = nil;
}

+(id)shareXMPPManagerInstance:(XMPPConfig *)config
{
    static XMPPChatManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (shareManager == nil) {
            shareManager = [[XMPPChatManager alloc] initWithConfig:config];
        }
    });
    
    return shareManager;
}

+(id)shareXMPPManagerInstance
{
    return [self shareXMPPManagerInstance:nil];
}

-(void)setConfig:(XMPPConfig *)config
{
    self.xmppConfig = config;
    self.xmppStream.hostName = self.xmppConfig.hostname;
    self.xmppStream.hostPort = self.xmppConfig.port;
}

-(id)initWithConfig:(XMPPConfig *)config
{
    self = [super init];
    if (self) {
        self.xmppConfig = config;
        [self setupStream];
    }
    return self;
}

-(XMPPStream *)xmppStream
{
    return _innerxmppStream;
}

-(XMPPRoster *)xmppRoster
{
    return _innerxmppRoster;
}

-(void)setupStream {
    if (_innerxmppStream != nil) {
        [self teardownStream];
    }
    
    _innerxmppStream = [[XMPPStream alloc] init];
    [_innerxmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    _innerxmppStream.enableBackgroundingOnSocket = YES;
    
    [_innerxmppStream setHostName:self.xmppConfig.hostname];
    [_innerxmppStream setHostPort:self.xmppConfig.port];
    
    _innerxmppReconnect = [[XMPPReconnect alloc] init];
    [_innerxmppReconnect activate:_innerxmppStream];
    [_innerxmppReconnect addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    
    _innerxmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
    _innerxmppRoster = [[XMPPRoster alloc] initWithRosterStorage:_innerxmppRosterStorage];
    [_innerxmppRoster addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    _innerxmppRoster.autoFetchRoster = YES;
    _innerxmppRoster.autoAcceptKnownPresenceSubscriptionRequests = NO;
    
    [_innerxmppRoster activate:_innerxmppStream];
    
    
    self.allowSelfSignedCertificates = NO;
    self.allowSSLHostNameMismatch = NO;
    
    if (![self connect]) {
//        [[[UIAlertView alloc]initWithTitle:@"" message:@"服务器维护中..." delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil]show];
    }
    
    
}

-(void)loginWithAnonymous
{
    self.XMPPmyJID = @"anonymous";
    self.XMPPmyPassword = @"";
    [self connect];
}

-(void)registerWithUsername:(NSString *)username password:(NSString *)password
{
    NSString *jidStr = [NSString stringWithFormat:@"%@@%@",username,self.xmppConfig.hostname];
    [self.innerxmppStream setMyJID:[XMPPJID jidWithString:jidStr]];
    NSError *error = nil;
    NSMutableArray *elements = [[NSMutableArray alloc] init];
    [elements addObject:[NSXMLElement elementWithName:@"username" stringValue:username]];
    [elements addObject:[NSXMLElement elementWithName:@"password" stringValue:password]];
    [elements addObject:[NSXMLElement elementWithName:@"name" stringValue:@"name"]];
    [elements addObject:[NSXMLElement elementWithName:@"email" stringValue:@"email@app.com"]];
    if (![_innerxmppStream registerWithElements:elements error:nil]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"创建帐号失败"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
    
//    if (![_innerxmppStream registerWithPassword:password error:&error]) {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"创建帐号失败"
//                                                            message:[error localizedDescription]
//                                                           delegate:nil
//                                                  cancelButtonTitle:@"Ok"
//                                                  otherButtonTitles:nil];
//        [alertView show];
//    }
}

-(void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    [self disConnect];
    self.XMPPmyJID = username;
    self.XMPPmyPassword = password;
    [self connect];
}

-(BOOL)connect
{
    if (![_innerxmppStream isDisconnected] && [[[_innerxmppStream myJID] user] isEqualToString:self.XMPPmyJID]) {
        return YES;
    }
    [_innerxmppStream disconnect];
    if (self.XMPPmyJID == nil || self.XMPPmyPassword == nil) {
        return NO;
    }
    
    [_innerxmppStream setMyJID:[XMPPJID jidWithUser:self.XMPPmyJID domain:self.xmppConfig.hostname resource:@"ios"]];
    NSError *error = nil;
    if (![_innerxmppStream connectWithTimeout:30 error:&error]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
		                                                    message:@"请检查你的网络设置,如仍有问题请联系我们(...)"
		                                                   delegate:nil
		                                          cancelButtonTitle:@"Ok"
		                                          otherButtonTitles:nil];
		[alertView show];
        
        return NO;
    }
    
    return YES;
}

-(void)disConnect {
    [self goOffline];
    [_innerxmppStream disconnect];
}

-(void)goOnline {
    XMPPPresence *presence = [XMPPPresence presence];
    [_innerxmppStream sendElement:presence];
}

-(void)goOffline
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
	[_innerxmppStream sendElement:presence];
}

- (void)addSomeBody:(NSString *)userId
{
    [_innerxmppRoster subscribePresenceToUser:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",userId,self.xmppConfig.hostname]]];
}

-(void)addFriendSubscribe:(NSString *)username
{
    NSLog(@"%@",username);
    XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",username,servername]];
    [_innerxmppRoster subscribePresenceToUser:jid];
}

- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    //断开链接处理
    NSLog(@"%s : %@",__FUNCTION__,error);
	
    //	if (!isXmppConnected)
    //	{
    //		DDLogError(@"Unable to connect to server. Check xmppStream.hostName");
    //	}
}

-(void)xmppStreamDidConnect:(XMPPStream *)sender
{
    //连接到服务器成功
    if ([[[sender myJID] user] isEqualToString:@"anonymous"]) {
        //匿名登录
        return;
    }
    
    //用户登录
    NSError *error = nil;
	if (![_innerxmppStream authenticateWithPassword:self.XMPPmyPassword error:&error])
	{
        //		DDLogError(@"Error authenticating: %@", error);
	}
}

- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    //用户信息服务器认证成功
	[self goOnline];
    [[NSNotificationCenter defaultCenter] postNotificationName:AuthorizedFinishNotification object:sender];
}

- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@"%s --> %@",__FUNCTION__,error);
}

- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
	return NO;
}

- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
    NSLog(@"%s : %@",__FUNCTION__,error);
}

- (void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence
{
    [[NSNotificationCenter defaultCenter] postNotificationName:NewFriendsRequstNotification object:presence];
}

#pragma mark -用户注册

-(void)xmppStreamDidRegister:(XMPPStream *)sender
{
    NSLog(@"%s",__FUNCTION__);
    NSLog(@"user : %@",[[sender myJID] user]);
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"创建帐号成功"
                                                        message:@""
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
    [alertView show];
}

-(void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error
{
    NSLog(@"%s",__FUNCTION__);
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"创建帐号失败"
                                                         message:@"用户名冲突"
                                                        delegate:nil
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
    [alertView show];
}

@end
